package com.damai.action.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.crypt.CryptFactory;
import com.citywithincity.crypt.IDataCrypt;
import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.JsonUtil;
import com.damai.error.ApiError;

class DecGetJson implements IGetJson {
	
	private IDataCrypt crypt = CryptFactory.getDataCrypt();
	
	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		int len = request.getContentLength();
		if(len<=0){
			len = Integer.parseInt(request.getHeader("totalLength"));
		}
		byte[] buffer = new byte[len];
		InputStream inputStream = request.getInputStream();
		IoUtil.read(buffer, inputStream);
		Customer customer = (Customer) request.getAttribute("customer");
		if(customer==null){
			throw new RuntimeException("应该有Customer但是没有，可能忘记写@Token");
		}
		try {
			buffer = crypt.decript(buffer, customer.getPinKey());
		} catch (Exception e) {
			throw new ApiError("数据解密失败，请稍后重试");
		}
		return JsonUtil.read(buffer);
	}

}
